package com.baiyue.exception;

import com.baiyue.result.CodeMsg;
import com.baiyue.result.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 统一异常处理
 * @author WuBo
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e) {
//        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getCm());
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        } else if(e instanceof MissingServletRequestParameterException){
            MissingServletRequestParameterException msx = (MissingServletRequestParameterException) e;
            String errors = msx.getParameterName();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(errors));
        }else if(e instanceof DuplicateKeyException){
            DuplicateKeyException de = (DuplicateKeyException) e;
            String errors = de.getMessage();
            return Result.error(CodeMsg.USERNAME_ALREADY_EXISTS.fillArgs(errors));
        }else if (e instanceof HttpRequestMethodNotSupportedException){
            HttpRequestMethodNotSupportedException hrms = (HttpRequestMethodNotSupportedException) e;
            String error = hrms.getMessage();
            return Result.error(CodeMsg.REQUEST_ILLEGAL.fillArgs(error));
        }else {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
